package com.hu.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class TaskPoolConfig {

    @Bean
    public Executor executor(){
        // 核心线程数 最大线程数 等待时间 等待单位 线程工厂 队列 拒绝策略
        // 分为CPU密集型和IO密集型
        int count = Runtime.getRuntime().availableProcessors(); // 获得核心数
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(count * 2); // 一般来说IO类型为CPU核心数 * 2,CPU类型是CPU核心数+1
        executor.setMaxPoolSize(count * 4);
        executor.setQueueCapacity(200000); //队列长度
        executor.setKeepAliveSeconds(60); // 活跃时间
        executor.setAwaitTerminationSeconds(60); // 设置关闭时阻止的最大秒数
        executor.setWaitForTasksToCompleteOnShutdown(true); // 等待所有任务执行完
        return executor;
    }
}
